import json
from typing import Dict, Optional
from threading import Lock
import requests
import random
import time

class ProxyPool:
    _instance = None
    _initialized = False

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, max_use_count: int = 5, min_pool_size: int = 10):
        if not ProxyPool._initialized:
            self.proxies: Dict[str, int] = {}  # 代理池，格式：{proxy: use_count}
            self.lock = Lock()
            self.max_use_count = max_use_count
            self.min_pool_size = min_pool_size
            ProxyPool._initialized = True

    def get_proxy(self) -> dict:
        """获取一个代理"""
        with self.lock:
            # 检查代理池大小，如果小于最小值则补充
            if len(self.proxies) < self.min_pool_size:
                self._add_new_proxies()
            
            # 获取使用次数最少的代理
            if self.proxies:
                proxy = min(self.proxies.items(), key=lambda x: x[1])[0]
                self.proxies[proxy] += 1
                
                # 如果代理使用次数超过限制，删除它
                if self.proxies[proxy] >= self.max_use_count:
                    del self.proxies[proxy]
                if isinstance(proxy, str):
                    return json.loads(proxy)

            
            # 如果代理池为空，获取新代理
            new_proxy = self._fetch_new_proxy()


            self.proxies[json.dumps(new_proxy)] = 1
            return new_proxy

    def _add_new_proxies(self):
        """补充代理到代理池中"""
        while len(self.proxies) < self.min_pool_size:
            new_proxy = json.dumps(self._fetch_new_proxy())

            if new_proxy and new_proxy not in self.proxies:
                if isinstance(new_proxy, dict):
                    new_proxy = json.dumps(new_proxy)
                self.proxies[new_proxy] = 0

    def _fetch_new_proxy(self) -> Optional[Dict]:
        """从代理服务获取新代理"""
        # 这里实现获取代理的具体逻辑
        # 示例：从代理API获取代理
        try:
            # 这里替换成实际的代理获取API
            response = requests.get('http://172.16.48.118:5000/get/')
            if response.status_code == 200:
                proxy_data = response.json()['proxy']
                proxies = {
                    'http': f"http://{proxy_data}",
                    'https': f"http://{proxy_data}"
                }
                # 根据实际API返回格式处理数据
                return proxies
        except Exception as e:
            print(f"获取代理时出错: {str(e)}")

        return None

    def remove_proxy(self, proxy: dict):
        """从代理池中移除指定代理"""
        proxy = json.dumps(proxy)
        with self.lock:
            if proxy in self.proxies:
                del self.proxies[proxy]

    def get_pool_status(self) -> Dict:
        """获取代理池状态"""
        with self.lock:
            return {
                "total_proxies": len(self.proxies),
                "proxies_usage": dict(self.proxies),
                "min_pool_size": self.min_pool_size,
                "max_use_count": self.max_use_count
            }

# 创建全局代理池实例
_default_proxy_pool = None

def init_proxy_pool(max_use_count: int = 5, min_pool_size: int = 10) -> ProxyPool:
    """初始化全局代理池"""
    global _default_proxy_pool
    if _default_proxy_pool is None:
        _default_proxy_pool = ProxyPool(max_use_count, min_pool_size)
    return _default_proxy_pool

def get_proxy() -> str:
    """获取一个代理的便捷函数"""
    global _default_proxy_pool
    if _default_proxy_pool is None:
        _default_proxy_pool = ProxyPool()
    return _default_proxy_pool.get_proxy()

def remove_proxy(proxy: str):
    """移除指定代理的便捷函数"""
    global _default_proxy_pool
    if _default_proxy_pool is not None:
        _default_proxy_pool.remove_proxy(proxy)

def get_pool_status() -> Dict:
    """获取代理池状态的便捷函数"""
    global _default_proxy_pool
    if _default_proxy_pool is None:
        return {"error": "代理池未初始化"}
    return _default_proxy_pool.get_pool_status()
